package demo3
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.geom.Matrix;

	import nape.geom.Vec2;
	import nape.phys.Body;
	import nape.phys.BodyType;
	import nape.shape.Polygon;
	import nape.space.Space;

	public final class BitmapDataBox
	{
		[Embed(source="box.jpg")]
		private static var _boxClass:Class;

		private static var boxBitmapData:BitmapData;

		private var boxBody:Body;
		private var boxContainer:Sprite;

		private var boxWidth:Number=111;
		private var boxHeight:Number=111;

		private var matrix:Matrix;

		public function BitmapDataBox()
		{
			boxBitmapData=new BitmapData(boxWidth, boxHeight);
			boxBitmapData.draw(new _boxClass());
		}

		public function initialize(container:DisplayObjectContainer, _posX:Number, _posY:Number, _space:Space):void
		{
			matrix=new Matrix();

			boxBody=new Body(BodyType.DYNAMIC, new Vec2(_posX, _posY));
			var shape:Polygon=new Polygon(Polygon.box(boxWidth, boxHeight));
			boxBody.shapes.add(shape);
			boxBody.space=_space;

			boxContainer=new Sprite();
			//container.addChild(boxContainer);
			boxContainer.x=_posX;
			boxContainer.y=_posY;

			matrix.identity();
			matrix.translate(-boxWidth / 2, -boxHeight / 2);
			boxContainer.graphics.beginBitmapFill(boxBitmapData, matrix);
			var pointIndex:int=0
			shape.localVerts.foreach(function(v:Vec2):void
			{
				if (pointIndex == 0)
				{
					boxContainer.graphics.moveTo(v.x, v.y);
				}
				else
				{
					boxContainer.graphics.lineTo(v.x, v.y);
				}
				pointIndex++;
			});
			boxContainer.graphics.endFill();

			boxBody.userData["target"]=this;
		}

		public function adjustDisplay():void
		{
			matrix.identity();
			//matrix.translate(-boxWidth / 2, -boxHeight / 2);
			matrix.rotate(boxBody.rotation)
			matrix.translate(boxBody.position.x, boxBody.position.y);
			boxContainer.transform.matrix=matrix;
		}
	}
}
